import 'dart:typed_data';
import 'dart:ui';
import 'package:lishi/detail.dart';
import 'package:lishi/toast.dart';
import 'package:flutter/material.dart';
import 'package:lishi/global.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

class ContentPage extends StatefulWidget {
  ContentPage({Key key, this.data}) : super(key: key);
  final data;

  @override
  _ContentPageState createState() => _ContentPageState();
}

class _ContentPageState extends State<ContentPage> {
  GlobalKey globalKey = GlobalKey();

  @override
  void initState() {
    super.initState();
  }

  Future<Uint8List> _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          globalKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      var status = await Permission.storage.status;
      print(status.isUndetermined);
      final result = await ImageGallerySaver.saveImage(pngBytes,
          quality: 100, name: "历史上的今天-" + widget.data['date'].toString());
      Toast.show(context,
          msg: '图片保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
    } catch (e) {
      print(e);
    }
    return null;
  }

  List<Widget> renderText(data) {
    List<Widget> list = [];
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      list.add(
        InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DetailPage(id: item['id'].toString()),
              ),
            );
          },
          child: Container(
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  (i + 1).toString(),
                  maxLines: 3,
                  style: TextStyle(
                    color: Global.fontColor,
                    fontSize: 17,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(width: 10),
                Expanded(
                  child: Text(
                    item['title'].toString() + '>>',
                    maxLines: 3,
                    style: TextStyle(
                      color: Global.fontColor,
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
      list.add(SizedBox(height: 10));
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return widget.data == null
        ? Container()
        : Container(
            padding: EdgeInsets.all(10),
            width: MediaQuery.of(context).size.width,
            // height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              color: Global.backgroundColor,
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                RepaintBoundary(
                  key: globalKey,
                  child: Container(
                    padding: EdgeInsets.all(30),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              widget.data['date'],
                              style: TextStyle(
                                color: Global.fontSecondColor,
                                fontSize: 18.5,
                                fontWeight: FontWeight.w400,
                              ),
                            )
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              '星期' + widget.data['weekday'].toString(),
                              style: TextStyle(
                                color: Global.fontSecondColor,
                                fontSize: 15,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                            SizedBox(width: 10),
                            Container(
                              width: 1,
                              height: 10,
                              decoration: BoxDecoration(
                                border: Border(
                                  left: BorderSide(
                                    color:
                                        Global.fontSecondColor.withOpacity(.3),
                                    width: 1.5,
                                  ),
                                ),
                              ),
                            ),
                            SizedBox(width: 10),
                            Text(
                              widget.data['weekdayEn'].toString(),
                              style: TextStyle(
                                color: Global.fontSecondColor,
                                fontSize: 15,
                                fontWeight: FontWeight.w400,
                              ),
                            )
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(width: 7),
                            Transform(
                              transform: Matrix4.identity()..scale(1.3, 1),
                              alignment: Alignment.center,
                              child: Text(
                                widget.data['day'].toString(),
                                style: TextStyle(
                                  color: Global.fontColor.withOpacity(.8),
                                  fontSize: 130,
                                  fontWeight: FontWeight.w100,
                                ),
                              ),
                            )
                          ],
                        ),
                        SizedBox(height: 20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(
                              child: Text(
                                widget.data['list'][0]['title'],
                                maxLines: 3,
                                style: TextStyle(
                                  color: Global.fontColor,
                                  fontSize: 23,
                                  fontWeight: FontWeight.w300,
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 20),
                      ],
                    ),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    IconButton(
                      icon: Icon(Icons.file_download),
                      color: Global.fontColor,
                      iconSize: 30,
                      onPressed: () {
                        _capturePng();
                      },
                    ),
                  ],
                ),
                SizedBox(height: 20),
                Container(
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.all(20),
                  margin: EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        color: Global.fontSecondColor.withOpacity(.2),
                        width: .5,
                      ),
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: renderText(widget.data['list']),
                  ),
                ),
              ],
            ),
          );
  }
}
